home *** CD-ROM | disk | FTP | other *** search
/ Scene 96 / Scene 96 International Edition (Zyklop Software) (Disc 2) (1997).iso / misc / coding / midas060 / src / loads3m.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-25  |  39.9 KB  |  1,272 lines

  1. /*      loads3m.c
  2.  *
  3.  * Generic Module Player Screamtracker 3 Module loader
  4.  *
  5.  * $Id: loads3m.c,v 1.15 1997/01/25 15:23:16 pekangas Exp $
  6.  *
  7.  * Copyright 1996,1997 Housemarque Inc.
  8.  *
  9.  * This file is part of the MIDAS Sound System, and may only be
  10.  * used, modified and distributed under the terms of the MIDAS
  11.  * Sound System license, LICENSE.TXT. By continuing to use,
  12.  * modify or distribute this file you indicate that you have
  13.  * read the license and understand and accept it fully.
  14. */
  15.  
  16. #include "lang.h"
  17. #include "mtypes.h"
  18. #include "errors.h"
  19. #include "mglobals.h"
  20. #include "mmem.h"
  21. #include "file.h"
  22. #include "sdevice.h"
  23. #include "gmplayer.h"
  24. #ifndef NOEMS
  25. #include "ems.h"
  26. #endif
  27. #include "mutils.h"
  28.  
  29.  
  30. /*#define CHECK_THE_HEAP*/
  31.  
  32. #ifdef CHECK_THE_HEAP
  33. #include <malloc.h>
  34. #endif
  35.  
  36.  
  37. RCSID(const char *loads3m_rcsid = "$Id: loads3m.c,v 1.15 1997/01/25 15:23:16 pekangas Exp $";)
  38.  
  39.  
  40.  
  41. /* Pass error code in variable "error" on, used in gmpLoadS3M(). */
  42. #define PASSERR() { LoadError(); PASSERROR(ID_gmpLoadS3M) }
  43.  
  44. /****************************************************************************\
  45. *
  46. * Function:     TestHeap(void)
  47. *
  48. * Description:  Test if the heap is corrupted. Watcom C ONLY! Implemented here
  49. *               because the Watcom _heapchk() often reports the heap is OK
  50. *               even though it isn't.
  51. *
  52. * Returns:      MIDAS error code
  53. *
  54. \****************************************************************************/
  55.  
  56. #if defined(CHECKTHEHEAP) && defined(__WC32__)
  57.     /* Maximum valid block in heap: */
  58. #define MAXBLK (2048*1024)
  59.  
  60. int TestHeap(void)
  61. {
  62.     static struct _heapinfo hinfo;
  63.     int         hstatus;
  64.     unsigned    len;
  65.  
  66.     hinfo._pentry = NULL;
  67.  
  68.     while ( 1 )
  69.     {
  70.         hstatus = _heapwalk(&hinfo);
  71.         if ( hstatus != _HEAPOK )
  72.             break;
  73.         len = hinfo._size;
  74.         if ( (len == 0) || (len > MAXBLK) || (len & 3) )
  75.             return errHeapCorrupted;
  76.     }
  77.  
  78.     if ( (hstatus == _HEAPEND) || (hstatus == _HEAPEMPTY) )
  79.         return OK;
  80.     return errHeapCorrupted;
  81. }
  82.  
  83. #define CHECKHEAP \
  84.     { \
  85.         if ( TestHeap() != OK ) \
  86.         { \
  87.             puts("HEAP CORRUPTED!"); \
  88.             ERROR(errHeapCorrupted, ID_gmpLoadXM); \
  89.             LoadError(); \
  90.             return errHeapCorrupted; \
  91.         } \
  92.     }
  93. #else
  94. #define CHECKHEAP
  95. #endif
  96.  
  97. /****************************************************************************\
  98. *       struct s3mHeader
  99. *       ----------------
  100. * Description:  Scream Tracker 3 module file header
  101. \****************************************************************************/
  102.  
  103. typedef struct
  104. {
  105.     char    name[28];        /* song name */
  106.     U8          num1A;                  /* 0x1A */
  107.     U8          type;                   /* file type */
  108.     U16         unused1;
  109.     U16         songLength;             /* number of orders */
  110.     U16         numInsts;               /* number of instruments */
  111.     U16         numPatts;               /* number of patterns */
  112.     U16         flags;
  113.  
  114. /*
  115.     struct
  116.     {
  117.         int     st2Vibrato : 1;
  118.         int     st2Tempo : 1;
  119.         int     ptSlides : 1;
  120.         int     zeroVolOpt : 1;
  121.         int     ptLimits : 1;
  122.         int     filter : 1;
  123.         int     fastVolSlide : 1;
  124.         int     unused : 9;
  125.     } flags;
  126. */
  127.     U16         trackerVer;             /* tracker version */
  128.     U16         formatVer;              /* file format version */
  129.     char    SCRM[4];        /* "SCRM" */
  130.     U8          masterVol;              /* master volume */
  131.     U8          speed;                  /* initial speed */
  132.     U8          tempo;                  /* initial tempo */
  133.     U8          masterMult;             /* master multiplier (bits 0-3),stereo (bit 4) */
  134.     U8          ultraClicks;            /* Ultraclick removal info */
  135.     U8          panningMagic;           /* 0FCh if panning infos exist */
  136.     U8          unused2[8];
  137.     U16         special;                /* pointer to special custom data */
  138.     U8          chanSettings[32];       /* channel settings */
  139.  
  140. } s3mHeader;
  141.  
  142.  
  143. /****************************************************************************\
  144. *       struct s3mPattern
  145. *       ----------------
  146. * Description:  Screamtracker 3 Module pattern
  147. \****************************************************************************/
  148.  
  149. typedef struct
  150. {
  151.     U16         pattDataSize;           /* pattern data size */
  152.     U8          data[EMPTYARRAY];       /* packed pattern data */
  153. } s3mPattern;
  154.  
  155.  
  156. /****************************************************************************\
  157. *       struct s3mInstHdr
  158. *       -----------------
  159. * Description:  Scream Tracker 3 module instrument file header
  160. \****************************************************************************/
  161.  
  162. typedef struct
  163. {
  164.     U8          type;                   /* instrument type */
  165.     char        dosName[12];            /* DOS filename (8+3) */
  166.     char        zero;                   /* 0 */
  167.     U16         samplePtr;              /* paragraph ptr to sample data */
  168.     U32         length;                 /* sample length */
  169.     U32         loopStart;              /* sample loop start */
  170.     U32         loopEnd;                /* sample loop end */
  171.     U8          volume;                 /* volume */
  172.     U8          disk;                   /* instrument disk number */
  173.     U8          pack;                   /* sample packing info (0 = raw,1 = DP30ADPCM1) */
  174.     U8          flags;                  /* bit0 = loop, bit1 = stereo,bit2 = 16-bit */
  175.     U32         c2Rate;                 /* C2 sampling rate */
  176.     U32         unused;
  177.     U16         gusPos;                 /* position in GUS memory / 32 */
  178.     U16         int512;
  179.     U32         intLastUsed;
  180.     char        iname[28];              /* instrument name */
  181.     char        SCRS[4];                /* "SCRS" if sample */
  182. } s3mInstHdr;
  183.  
  184.  
  185. /* Conversion table from Screamtracker command number to GMP ones: */
  186. static uchar s3mCommands[26] =
  187. {
  188.     gmpcSetSpeed,               /* A - Set speed */
  189.     gmpcPositionJump,           /* B - Position jump */
  190.     gmpcPatternBreak,           /* C - Pattern break */
  191.     gmpcVolumeSlide,            /* D - Volume slide */
  192.     gmpcSlideDown,              /* E - Slide down */
  193.     gmpcSlideUp,                /* F - Slide up */
  194.     gmpcTonePortamento,         /* G - Tone portamento */
  195.     gmpcVibrato,                /* H - Vibrato */
  196.     gmpcNone,                   /* I - Tremor */
  197.     gmpcArpeggio,               /* J - Arpeggio */
  198.     gmpcVibVSlide,              /* K - Vibrato + volume slide */
  199.     gmpcTPortVSlide,            /* L - Tone portamento + volume slide */
  200.     gmpcNone,                   /* M - Unused */
  201.     gmpcNone,                   /* N - Unused */
  202.     gmpcSampleOffset,           /* O - Set sample offset */
  203.     gmpcNone,                   /* P - Unused */
  204.     gmpcS3MRetrig,              /* Q - ST3 extended retrig */
  205.     gmpcTremolo,                /* R - Tremolo */
  206.     gmpcNone,                   /* S - S-commands (table below) */
  207.     gmpcSetTempo,               /* T - Set tempo */
  208.     gmpcNone,                   /* U - Fine vibrato */
  209.     gmpcSetMVolume,             /* V - Set master volume */
  210.     gmpcMusicSync,              /* W - Music synchronization (extension) */
  211.     gmpcSetPanning,             /* X - Set panning (extension) */
  212.     gmpcNone,                   /* Y - Unused */
  213.     gmpcSetPanning16            /* Z - Set panning (extension) */
  214. };
  215.  
  216. /* Conversion table from Screamtracker S-command numbers to GMP commands: */
  217. static uchar s3mSCommands[16] =
  218. {
  219.     gmpcNone,                   /* S0 - Set filter */
  220.     gmpcNone,                   /* S1 - Set glissando control */
  221.     gmpcNone,                   /* S2 - Set finetune */
  222.     gmpcNone,                   /* S3 - Set vibrato waveform */
  223.     gmpcNone,                   /* S4 - Set tremolo waveform */
  224.     gmpcNone,                   /* S5 - Unused */
  225.     gmpcNone,                   /* S6 - Unused */
  226.     gmpcNone,                   /* S7 - Unused */
  227.     gmpcSetPanning16,           /* S8 - Set panning */
  228.     gmpcNone,                   /* S9 - Unused */
  229.     gmpcNone,                   /* SA - Stereo control (obsolete) */
  230.     gmpcPatternLoop,            /* SB - Pattern loop */
  231.     gmpcNoteCut,                /* SC - Note cut */
  232.     gmpcNoteDelay,              /* SD - Note delay */
  233.     gmpcPatternDelay,           /* SE - Pattern delay */
  234.     gmpcNone                    /* SF - Invert loop (unused in ST3) */
  235. };
  236.  
  237.  
  238.  
  239. /****************************************************************************\
  240. *       Module loader buffers and file handle. These variables are static
  241. *       instead of local so that a separate deallocation can be used which
  242. *       will be called before exiting in error situations
  243. \****************************************************************************/
  244. static fileHandle f;                    /* file handle for module file */
  245. static int      fileOpened;             /* 1 if module file has been opened */
  246. static gmpModule *module;               /* pointer to GMP module structure */
  247. static s3mHeader *header;               /* pointer to S3M module header */
  248. static uchar    *instUsed;              /* instrument used flags */
  249. static s3mPattern *s3mPatt;             /* pointer to S3M pattern data */
  250. static gmpPattern *convPatt;            /* pointer to converted pattern data*/
  251. static U16      *instPtrs;              /* instrument paragraph pointers */
  252. static U16      *pattPtrs;              /* pattern paragraph pointers */
  253. static uchar    *smpBuf;                /* sample loading buffer */
  254. static unsigned numChans;               /* number of channels in module */
  255. static unsigned maxChan;                /* maximum enabled channel */
  256. static unsigned maxInstUsed;            /* maximum instrument used */
  257. static s3mInstHdr s3mi;
  258.  
  259.  
  260.  
  261.  
  262.  
  263. /****************************************************************************\
  264. *
  265. * Function:     int ConvertPattern(s3mPattern *srcPatt, gmpPattern *destPatt,
  266. *                   unsigned *convLen);
  267. *
  268. * Description:  Converts a pattern from S3M to GMP internal format.
  269. *               Also updates instUsed flags.
  270. *
  271. * Input:        s3mPattern *srcPatt     pointer to pattern in S3M format
  272. *               gmpPattern *destPatt    pointer to destination GMP pattern
  273. *               unsigned *convLen       pointer to converted pattern length
  274. *
  275. * Returns:      MIDAS error code. Converted pattern length (in bytes,
  276. *               including header) is written to *convLen.
  277. *
  278. \****************************************************************************/
  279.  
  280. static int ConvertPattern(s3mPattern *srcPatt, gmpPattern *destPatt,
  281.     unsigned *convLen)
  282. {
  283.     uchar       *src = &srcPatt->data[0];
  284.     uchar       *dest = &destPatt->data[0];
  285.     int         row;
  286.     unsigned    len;
  287.     U8          note, inst, command, infobyte, vol, compInfo;
  288.     U8          s3mComp;
  289.  
  290. /*
  291.         Packed data consits of following entries:
  292.         BYTE:what  0=end of row
  293.                    &31=channel
  294.                    &32=follows;  BYTE:note, BYTE:instrument
  295.                    &64=follows;  BYTE:volume
  296.                    &128=follows; BYTE:command, BYTE:info
  297. */
  298.     /* Check if the pattern is empty: */
  299.     if ( (srcPatt->pattDataSize == 0) || (srcPatt == NULL) )
  300.     {
  301.         /* Write row end marker for each row: */
  302.         for ( row = 0; row < 64; row++ )
  303.             *(dest++) = 0;
  304.  
  305.         /* Write number of rows to pattern header: */
  306.         destPatt->rows = 64;
  307.  
  308.         /* Write converted pattern length to header and return it in
  309.            *convLen: */
  310.         *convLen = destPatt->length = 64 + sizeof(gmpPattern);
  311.         return OK;
  312.     }
  313.  
  314.     for ( row = 0; row < 64; row++ )
  315.     {
  316.         while ( *src != 0 )
  317.         {
  318.             /* No data for this channel yet: */
  319.             compInfo = 0;
  320.             note = 0xFF;
  321.             inst = 0xFF;
  322.             command = 0;
  323.             infobyte = 0;
  324.             vol = 0;
  325.  
  326.             /* Get note number/compression info from pattern data: */
  327.             s3mComp = *src++;
  328.  
  329.             /* Check if there is a new note and instrument: */
  330.             if ( s3mComp & 32 )
  331.             {
  332.                 /* Check that the note is not key off and convert it to GMP
  333.                    internal format: */
  334.                 if ( ( *src < 0x7f ) || ( *src == 0xfe ) || ( *src == 0xff ) )
  335.                     note = *src;
  336.                 src++;
  337.  
  338.                 /* Get the instrument number: */
  339.                 if ( *src <= module->numInsts )
  340.                     inst = (*src) - 1;
  341.  
  342.                 src++;
  343.  
  344.                 /* Check if the instrument number if above maximum instrument
  345.                    number used: */
  346.                 if ( inst <= 100 )
  347.                 {
  348.                     if ( inst < module->numInsts )
  349.                     {
  350.                         if ( inst > maxInstUsed )
  351.                             maxInstUsed = inst;
  352.  
  353.                         /* Mark instrument used: */
  354.                         instUsed[inst] = 1;
  355.                     }
  356.                 }
  357.                 /* Mark that there is a new note and/or instrument: */
  358.                 compInfo |= 32;
  359.  
  360.                 if ( numChans <= (unsigned) (s3mComp & 31) )
  361.                     numChans = (s3mComp & 31) + 1;
  362.             }
  363.  
  364.             /* Check if there is a volume column byte: */
  365.             if ( s3mComp & 64 )
  366.             {
  367.                 /* Get the volume column byte: */
  368.                 vol = *(src++);
  369.  
  370.                 if ( vol > 63 ) vol = 63;
  371.  
  372.                 /* Mark that there is a volume column byte: */
  373.                 compInfo |= 64;
  374.             }
  375.  
  376.             /* Check if there is a command: */
  377.             if ( s3mComp & 128 )
  378.             {
  379.                 /* Get the command number: */
  380.                 command = *(src++);
  381.  
  382.                 /* Get the infobyte: */
  383.                 infobyte = *(src++);
  384.             }
  385.  
  386.             /* If there is a command or an infobyte we need to write the
  387.                command to the destination pattern: */
  388.             if ( (command > 0) && (command < 26 ) )
  389.             {
  390.                 switch ( command )
  391.                 {
  392.                     case 19:
  393.                         /* Command S - check actual command number: */
  394.                         command = s3mSCommands[infobyte >> 4];
  395.                         infobyte = infobyte & 0x0F;
  396.                         break;
  397.  
  398.                     default:
  399.                         /* Convert command to GMP command number: */
  400.                         command = s3mCommands[command - 1];
  401.                         break;
  402.                 }
  403.  
  404.                 /* Mark that there is a command: */
  405.                 if ( command != gmpcNone )
  406.                     compInfo |= 128;
  407.             }
  408.  
  409.             /* If the compression information is nonzero, there is some
  410.                data for this channel: */
  411.             if ( ( compInfo & 0xE0 ) != 0 )
  412.             {
  413.                 /* Set channel number to lower 5 bits of the compression info
  414.                    and write it to destination: */
  415.                 compInfo |= ( s3mComp & 31 );
  416.                 if ( (unsigned) (s3mComp & 31) <= maxChan )
  417.                 {
  418.                     *(dest++) = compInfo;
  419.  
  420.                     /* Check if there a note+instrument pair: */
  421.                     if ( compInfo & 32 )
  422.                     {
  423.                         /* Write note and instrument numbers: */
  424.                         *(dest++) = note;
  425.                         *(dest++) = inst;
  426.                     }
  427.  
  428.                     /* Check if there is a volume column byte: */
  429.                     if ( compInfo & 64 )
  430.                     {
  431.                         /* Write the volume column byte: */
  432.                         *(dest++) = vol;
  433.                     }
  434.  
  435.                     /* Check if there is a command: */
  436.                     if ( compInfo & 128 )
  437.                     {
  438.                         /* Write command and command infobyte: */
  439.                         *(dest++) = command;
  440.                         *(dest++) = infobyte;
  441.                     }
  442.                 }
  443.             }
  444.         }
  445.  
  446.         /* Write row end marker: */
  447.         *(dest++) = 0;
  448.         src++;
  449.     }
  450.  
  451.     /* Write number of rows to pattern header: */
  452.     destPatt->rows = 64;
  453.  
  454.     /* Calculate converted pattern length: */
  455.     len = (unsigned) (dest  - ((uchar*) destPatt));
  456.  
  457.     /* Write converted pattern length to header and return it in *convLen: */
  458.     destPatt->length = len;
  459.     *convLen = len;
  460.  
  461.     return OK;
  462. }
  463.  
  464.  
  465.  
  466.  
  467. /****************************************************************************\
  468. *
  469. * Function:     void LoadError(void)
  470. *
  471. * Description:  Stops loading the module, deallocates all buffers and closes
  472. *               the file.
  473. *
  474. \****************************************************************************/
  475.  
  476. #define condFree(x) { if ( x != NULL ) if ( memFree(x) != OK) return; }
  477.  
  478. static void LoadError(void)
  479. {
  480.     /* Close file if opened. Do not process errors. */
  481.     if ( fileOpened )
  482.         if ( fileClose(f) != OK )
  483.             return;
  484.  
  485.     /* Attempt to deallocate module if allocated. Do not process errors. */
  486.     if ( module != NULL )
  487.         if ( gmpFreeModule(module) != OK )
  488.             return;
  489.  
  490.     /* Deallocate structures if allocated: */
  491.     condFree(header)
  492.     condFree(instUsed)
  493.     condFree(smpBuf)
  494. }
  495.  
  496.  
  497.  
  498.  
  499. /****************************************************************************\
  500. *
  501. * Function:     int gmpLoadS3M(char *fileName, int addSD, mpModule **module)
  502. *
  503. * Description:  Loads a Scream Tracker 3 module to memory in Generic Module
  504. *               Player module format
  505. *
  506. * Input:        char *fileName          module file name
  507. *               int addSD               1 if module samples should be added to
  508. *                                       the current Sound Device, 0 if not
  509. *               int (*SampleCallback)(...)  pointer to callback function that
  510. *                                       will be called after sample has been
  511. *                                       added to Sound Device, but before
  512. *                                       sample data is deallocated
  513. *               mpModule **module       pointer to GMP module pointer
  514. *
  515. * Returns:      MIDAS error code
  516. *
  517. \****************************************************************************/
  518.  
  519. int CALLING gmpLoadS3M(char *fileName, int addSD, int
  520.     (CALLING *SampleCallback)(sdSample *sdsmp, gmpSample *gmpsmp),
  521.     gmpModule **_module)
  522. {
  523.     int             error;              /* MIDAS error code */
  524.     gmpInstrument   *inst;
  525.     uchar           *panningInfos;
  526.     unsigned        i;
  527.     ulong           maxSample;
  528.     static unsigned convPattLen;
  529.     unsigned        slength;
  530.     gmpSample       *sample;
  531.     uchar           *temp;
  532.     static sdSample sdSmp;
  533.     int             n;
  534. #ifndef NOEMS
  535.     uchar           *patt;
  536. #endif
  537.     int             panValue;
  538.     unsigned        numS3MPatterns;
  539.     unsigned        numUsedPatterns;
  540.  
  541.  
  542.     /* point buffers to NULL and set fileOpened to 0 so that LoadError()
  543.        can be called at any point: */
  544.     fileOpened = 0;
  545.     module = NULL;
  546.     header = NULL;
  547.     instUsed = NULL;
  548.     s3mPatt = NULL;
  549.     convPatt = NULL;
  550.     instPtrs = NULL;
  551.     pattPtrs = NULL;
  552.     smpBuf = NULL;
  553.  
  554.     /* Clear other loader variables: */
  555.     maxInstUsed = 0;
  556.  
  557.     /* Allocate memory for Screamtracker module header: */
  558.     if ( (error = memAlloc(sizeof(s3mHeader), (void**) &header)) != OK )
  559.         PASSERR()
  560.  
  561.     /* Open module file: */
  562.     if ( (error = fileOpen(fileName, fileOpenRead, &f)) != OK )
  563.         PASSERR()
  564.     fileOpened = 1;
  565.  
  566.     /* Allocate memory for the module structure: */
  567.     if ( (error = memAlloc(sizeof(gmpModule), (void**) &module)) != OK )
  568.         PASSERR()
  569.  
  570.     /* Clear module structure so that it can safely be deallocated with
  571.        gmpFreeModule() at any point: */
  572.     module->panning = NULL;
  573.     module->songData = NULL;
  574.     module->instruments = NULL;
  575.     module->patterns = NULL;
  576.  
  577.     /* read Screamtracker module header: */
  578.     if ( (error = fileRead(f, header, sizeof(s3mHeader))) != OK )
  579.         PASSERR()
  580.  
  581.     numChans = 0;
  582.  
  583.     /* Check the module signature: */
  584.     if ( !(mMemEqual(&header->SCRM[0], "SCRM", 4) ) )
  585.     {
  586.         ERROR(errInvalidModule, ID_gmpLoadS3M);
  587.         LoadError();
  588.         return errInvalidModule;
  589.     }
  590.  
  591.  
  592.     /* Copy song name: */
  593.     mMemCopy(&module->name[0], &header->name[0], 28);
  594.     module->name[28] = 0;                   /* force terminating '\0' */
  595.  
  596.     module->songLength = header->songLength;    /* copy song length */
  597.     module->numInsts = header->numInsts;    /* set number of instruments */
  598.     numS3MPatterns = header->numPatts;      /* store number of patterns */
  599.     module->numPatts = 0;                   /* not really known yet! */
  600.     module->playMode = gmpST3;              /* set ST3 playing mode */
  601.     module->masterVolume = header->masterVol; /* copy master volume */
  602.     module->speed = header->speed;          /* initial speed */
  603.     module->tempo = header->tempo;          /* initial tempo */
  604.  
  605.     /* Copy some flags */
  606.     module->playFlags.ptLimits = ( header->flags & 0x10 ) >> 4;
  607.     module->playFlags.fastVolSlides = ( header->flags & 0x40 ) >> 6;
  608.     if ( header->trackerVer < 0x1320 )
  609.         module->playFlags.fastVolSlides = 1;
  610.  
  611.     module->restart = 0;
  612.  
  613. #ifdef DEBUGMESSAGES
  614.     puts("Header ready");
  615. #endif
  616.     CHECKHEAP
  617.  
  618.     /* Allocate memory for song data: */
  619.     if ( (error = memAlloc(sizeof(ushort) * module->songLength,
  620.         (void**) &module->songData)) != OK )
  621.         PASSERR()
  622.  
  623.     /* read song data: */
  624.     if ( (error = fileRead(f, module->songData, sizeof(uchar) *
  625.         module->songLength)) != OK )
  626.         PASSERR()
  627.  
  628.     /* Calculate real song length: (exclude 0xFF bytes from end) */
  629.     for ( n = (module->songLength - 1); module->songData[n] == 0xFF; n-- );
  630.         module->songLength = n + 1;
  631.  
  632.     /* Convert song data and find the highest pattern number used: */
  633.     temp = (uchar*) module->songData;
  634.     numUsedPatterns = 0;
  635.     for ( n = module->songLength - 1; n >= 0 ; n-- )
  636.     {
  637.         switch ( temp[n] )
  638.         {
  639.             case 0xfe:
  640.                 module->songData[n] = 0xfffe;
  641.                 break;
  642.  
  643.             case 0xff:
  644.                 module->songData[n] = 0xffff;
  645.                 break;
  646.  
  647.             default:
  648.                 module->songData[n] = temp[n];
  649.                 if ( temp[n] >= numUsedPatterns )
  650.                     numUsedPatterns = temp[n] + 1;
  651.         }
  652.     }
  653.  
  654.     module->numPatts = numUsedPatterns;
  655.  
  656.     /* check that song length is nonzero: */
  657.     if ( module->songLength == 0 )
  658.     {
  659.         ERROR(errInvalidModule, ID_gmpLoadS3M);
  660.         LoadError();
  661.         return errInvalidModule;
  662.     }
  663.  
  664. #ifdef DEBUGMESSAGES
  665.     puts("Song data ready");
  666.     printf("Num.patts: %i\n", module->numPatts);
  667. #endif
  668.     CHECKHEAP
  669.  
  670.     /* Allocate memory for pattern pointers: */
  671.     if ( (error = memAlloc(4 * module->numPatts,
  672.         (void**) &module->patterns)) != OK )
  673.         PASSERR()
  674.  
  675.     /* Set all pattern pointers to NULL to mark them unallocated: */
  676.     for ( i = 0; i < module->numPatts; i++ )
  677.         module->patterns[i] = NULL;
  678.  
  679.     /* Allocate memory for instrument pointers: */
  680.     if ( (error = memAlloc(sizeof(gmpInstrument*) * module->numInsts,
  681.         (void**) &module->instruments)) != OK )
  682.         PASSERR()
  683.  
  684.     /* Set all instrument pointers to NULL to mark them unallocated: */
  685.     for ( i = 0; i < module->numInsts; i++ )
  686.         module->instruments[i] = NULL;
  687.  
  688.     /* Allocate memory for instrument used flags: */
  689.     if ( (error = memAlloc(module->numInsts, (void**)&instUsed)) != OK )
  690.         PASSERR()
  691.  
  692.     /* Mark all instruments unused: */
  693.     for ( i = 0; i < module->numInsts; i++ )
  694.         instUsed[i] = 0;
  695.  
  696.      /* Allocate memory for instrument paragraph pointers: */
  697.     if ( (error = memAlloc(sizeof(U16) * module->numInsts, (void**)
  698.         &instPtrs)) != OK )
  699.         PASSERR()
  700.  
  701.     /* Read instrument pointers: */
  702.     if ( (error = fileRead(f, instPtrs, sizeof(U16) * module->numInsts))
  703.         != OK )
  704.         PASSERR()
  705.  
  706.     /* Allocate memory for S3M file pattern pointers: */
  707.     if ( (error = memAlloc(sizeof(U16) * numS3MPatterns, (void**)
  708.         &pattPtrs)) != OK )
  709.         PASSERR()
  710.  
  711.     /* Read pattern pointers: */
  712.     if ( (error = fileRead(f, pattPtrs, sizeof(U16) * numS3MPatterns))
  713.         != OK )
  714.         PASSERR()
  715.  
  716. #ifdef DEBUGMESSAGES
  717.     puts("Misc. pointers ready");
  718. #endif
  719.     CHECKHEAP
  720.  
  721.     /* Allocate memory for channel initial panning positions: */
  722.     if ( (error = memAlloc(32 * sizeof(int), (void**) &module->panning))
  723.         != OK )
  724.         PASSERR()
  725.  
  726.     if ( header->panningMagic == 0xFC )
  727.     {
  728.         /* Allocate memory for panning infos: */
  729.         if ( (error = memAlloc(32 * sizeof(uchar),
  730.             (void**) &panningInfos)) != OK )
  731.             PASSERR()
  732.  
  733.         /* Read panning infos: */
  734.         if ( ( error = fileRead(f, panningInfos, 32 * sizeof(uchar)) ) != OK )
  735.             PASSERR()
  736.  
  737.         /* Convert panning values: */
  738.         for (i = 0; i < 32; i++)
  739.         {
  740.             if ( header->chanSettings[i] > 15 )
  741.             {
  742.                 module->panning[i] = 0x40;
  743.             }
  744.             else
  745.             {
  746.                 maxChan = i;
  747.                 if ( panningInfos[i] & 0x20 )
  748.                 {
  749.                     panValue = panningInfos[i] & 0xF;
  750.                     if ( panValue < 7 )
  751.                     {
  752.                         module->panning[i] = 8 * panValue;
  753.                     }
  754.                     else
  755.                     {
  756.                         if ( panValue > 8 )
  757.                             module->panning[i] = 0x80 - (15 - panValue) * 8;
  758.                         else
  759.                             module->panning[i] = 0x40;
  760.                     }
  761.                 }
  762.                 else
  763.                 {
  764.                     if (header->chanSettings[i] < 8)
  765.                         module->panning[i] = 0x00;
  766.                     else
  767.                         module->panning[i] = 0x80;
  768.                 }
  769.             }
  770.         }
  771.  
  772.         /* Free panning infos: */
  773.         if ( (error = memFree(panningInfos)) != OK )
  774.             PASSERR()
  775.         panningInfos = NULL;
  776.     }
  777.     else
  778.     {
  779.         /* copy default channel panning settings: */
  780.         for (i = 0; i < 32; i++)
  781.         {
  782.             if (header->chanSettings[i] > 15)
  783.                 module->panning[i] = 0;
  784.             else
  785.             {
  786.                 maxChan = i;
  787.                 if (header->chanSettings[i] < 8)
  788.                     module->panning[i] = 0x00;
  789.                 else
  790.                     module->panning[i] = 0x80;
  791.             }
  792.         }
  793.     }
  794.  
  795. #ifdef DEBUGMESSAGES
  796.     puts("Panning ready");
  797. #endif
  798.     CHECKHEAP
  799.  
  800.     /* Find maximum sample length: */
  801.     maxSample = 0;
  802.     for ( i = 0; i < module->numInsts; i++ )
  803.     {
  804.         /* Seek to instrument header in file: */
  805.         if ( (error = fileSeek(f, 16L * instPtrs[i], fileSeekAbsolute))
  806.             != OK )
  807.             PASSERR()
  808.  
  809.         /* Read instrument header from file: */
  810.         if ( (error = fileRead(f, &s3mi, sizeof(s3mInstHdr))) != OK )
  811.             PASSERR()
  812.  
  813.         if ( maxSample < s3mi.length )
  814.             maxSample = s3mi.length;
  815.     }
  816.  
  817.     /* Check that the maximum sample length is below the Sound Device limit:*/
  818.     if ( maxSample > SMPMAX )
  819.     {
  820.         ERROR(errInvalidInst, ID_gmpLoadS3M);
  821.         LoadError();
  822.         return errInvalidInst;
  823.     }
  824.  
  825. #ifdef DEBUGMESSAGES
  826.     puts("Max. sample ready");
  827.     printf("Max. sample: %i\n", maxSample);
  828. #endif
  829.     CHECKHEAP
  830.  
  831.     /* Allocate memory for pattern loading buffer: */
  832.     if ( (error = memAlloc(32 * 64 * 6 + sizeof(s3mPattern),
  833.         (void**) &s3mPatt)) != OK )
  834.         PASSERR()
  835.  
  836.     /* Allocate memory for pattern conversion buffer: (maximum GMP pattern
  837.        data size is 6 bytes per row per channel plus header) */
  838.     if ( (error = memAlloc(32 * 64 * 6 + sizeof(gmpPattern),
  839.         (void**) &convPatt)) != OK )
  840.         PASSERR()
  841.  
  842. #ifdef DEBUGMESSAGES
  843.     puts("Ready for conversion");
  844. #endif
  845.     CHECKHEAP
  846.  
  847.     /* Load and convert all patterns: */
  848.     for ( i = 0; i < module->numPatts; i++ )
  849.     {
  850.         if ( (i < numS3MPatterns) && (pattPtrs[i] != 0) )
  851.         {
  852. #ifdef DEBUGMESSAGES
  853.             puts("Seek");
  854. #endif
  855.             CHECKHEAP
  856.             /* Seek to pattern beginning in file: */
  857.             if ( (error = fileSeek(f, 16L * pattPtrs[i], fileSeekAbsolute))
  858.                 != OK )
  859.                 PASSERR()
  860.  
  861. #ifdef DEBUGMESSAGES
  862.             puts("Read pattern length");
  863. #endif
  864.             CHECKHEAP
  865.             /* Read pattern length from file: */
  866.             if ( (error = fileRead(f, &s3mPatt->pattDataSize, sizeof(U16))) != OK )
  867.                 PASSERR()
  868.  
  869. #ifdef DEBUGMESSAGES
  870.             printf("Patt.len: %i\n", s3mPatt->pattDataSize);
  871.             puts("Read pattern data");
  872. #endif
  873.             CHECKHEAP
  874.             /* Read pattern data from file: */
  875.             if ( (error = fileRead(f, &s3mPatt->data[0], s3mPatt->pattDataSize)) != OK )
  876.                 PASSERR()
  877.         }
  878.         else
  879.         {
  880.             s3mPatt->pattDataSize = 0;
  881. #ifdef DEBUGMESSAGES
  882.             puts("Empty pattern");
  883. #endif
  884.         }
  885. #ifdef DEBUGMESSAGES
  886.         puts("Convert pattern");
  887. #endif
  888.         CHECKHEAP
  889.  
  890.         /* Convert the pattern data, checking the instruments used: */
  891.         if ( (error = ConvertPattern(s3mPatt, convPatt, &convPattLen))
  892.             != OK )
  893.             PASSERR()
  894.  
  895. #if 0
  896. #ifndef NOEMS
  897.         if ( mUseEMS == 1 )             /* is EMS memory used? */
  898.         {
  899.             /* Allocate EMS for converted pattern data for current pattern in
  900.                 module: */
  901.             if ( (error = emsAlloc(convPattLen, (emsBlock**)
  902.                 &module->patterns[i])) != OK )
  903.                 PASSERR()
  904.  
  905.             /* Map the allocated EMS block to conventional memory: */
  906.             if ( (error = emsMap((emsBlock*) module->patterns[i],
  907.                 (void**) &patt)) != OK)
  908.                 PASSERR()
  909.  
  910.             /* Copy the converted pattern data to the EMS block: */
  911.             mMemCopy(patt, convPatt, convPattLen);
  912.         }
  913.         else
  914. #endif
  915.  
  916. #endif
  917.         {
  918. #ifdef DEBUGMESSAGES
  919.             printf("Alloc mem: %i\n", convPattLen);
  920. #endif
  921.             CHECKHEAP
  922.             /* Allocate memory for converted pattern data for current pattern
  923.                 in module: */
  924.             if ( (error = memAlloc(convPattLen, (void**)&module->patterns[i]))
  925.                 != OK )
  926.                 PASSERR()
  927.  
  928.  
  929. #ifdef DEBUGMESSAGES
  930.             puts("Copy pattern");
  931. #endif
  932.             CHECKHEAP
  933.             /* Copy the converted pattern data: */
  934.             mMemCopy(module->patterns[i], convPatt, convPattLen);
  935.         }
  936. #ifdef DEBUGMESSAGES
  937.         printf("Pattern %i, Conv.len: %i\n", i, convPattLen);
  938. #endif
  939.         CHECKHEAP
  940.     }
  941.  
  942.     maxChan++;
  943.     /* store number of channels */
  944.     module->numChannels = ( maxChan < numChans ) ? maxChan : numChans;
  945. #ifdef DEBUGMESSAGES
  946.     printf("Num.channels: %i\n", module->numChannels);
  947. #endif
  948.     CHECKHEAP
  949.  
  950.     /* Deallocate pattern paragraph pointers: */
  951.     if ( (error = memFree(pattPtrs)) != OK )
  952.         PASSERR()
  953.     pattPtrs = NULL;
  954.  
  955.     /* Deallocate pattern conversion buffer: */
  956.     if ( (error = memFree(convPatt)) != OK )
  957.         PASSERR()
  958.     convPatt = NULL;
  959.  
  960.     /* Deallocate pattern loading buffer: */
  961.     if ( (error = memFree(s3mPatt)) != OK )
  962.         PASSERR()
  963.     s3mPatt = NULL;
  964.  
  965. #ifdef DEBUGMESSAGES
  966.     puts("Pattern conversion ready");
  967. #endif
  968.     CHECKHEAP
  969.  
  970.     /* If samples should be added to Sound Device, allocate memory for sample
  971.        loading buffer: */
  972.     if ( addSD )
  973.     {
  974.         if ( (error = memAlloc(maxSample, (void**) &smpBuf)) != OK )
  975.             PASSERR()
  976.     }
  977.  
  978.     if ( maxInstUsed > module->numInsts )
  979.         module->numInsts = maxInstUsed;
  980.  
  981. #ifdef DEBUGMESSAGES
  982.     printf("Max.inst. used: %i\n", maxInstUsed);
  983. #endif
  984.     CHECKHEAP
  985.  
  986.     /* Load all samples and convert sample and instrument data: */
  987.     for ( i = 0; i < module->numInsts; i++ )
  988.     {
  989.         /* Seek to instrument header in file: */
  990.         if ( (error = fileSeek(f, 16L * instPtrs[i], fileSeekAbsolute))
  991.             != OK )
  992.             PASSERR()
  993.  
  994.         /* Read instrument header from file: */
  995.         if ( (error = fileRead(f, &s3mi, sizeof(s3mInstHdr))) != OK )
  996.             PASSERR()
  997.  
  998.         /* Allocate memory for this instrument structure: (add space for one
  999.            sample if the instrument is used) */
  1000.         if ( instUsed[i] )
  1001.         {
  1002.             if ( (error = memAlloc(sizeof(gmpInstrument) + sizeof(gmpSample),
  1003.                 (void**) &module->instruments[i])) != OK )
  1004.                 PASSERR()
  1005.         }
  1006.         else
  1007.         {
  1008.             if ( (error = memAlloc(sizeof(gmpInstrument),
  1009.                 (void**) &module->instruments[i])) != OK )
  1010.                 PASSERR()
  1011.         }
  1012.  
  1013.         /* Point inst to current instrument structure: */
  1014.         inst = module->instruments[i];
  1015.  
  1016.         /* Mark there are no sample for the instrument: */
  1017.         inst->numSamples = 0;
  1018.  
  1019.         /* Copy instrument name: */
  1020.         mMemCopy(&inst->name[0], &s3mi.iname[0], 28);
  1021.         inst->name[28] = 0;             /* force terminating '\0' */
  1022.  
  1023.         /* Mark the instrument has no sample number table for keyboard
  1024.            notes: */
  1025.         inst->noteSamples = NULL;
  1026.  
  1027.         /* Mark the instrument has no volume or panning envelopes: */
  1028.         inst->volEnvelope = NULL;
  1029.         inst->panEnvelope = NULL;
  1030.  
  1031.         /* Mark the instrument has no FT2 auto-vibrato: */
  1032.         inst->vibType = inst->vibSweep = inst->vibDepth = inst->vibRate = 0;
  1033.  
  1034.         /* Check if the instrument is used in the module: */
  1035.         if ( instUsed[i] )
  1036.         {
  1037.             /* The instrument is used - mark it used and point sample to its
  1038.                sample information: */
  1039.             inst->used = 1;
  1040.             inst->numSamples = 1;
  1041.             sample = &inst->samples[0];
  1042.  
  1043.             /* Mark there is no sample data and the sample has not been added
  1044.                to Sound Device: */
  1045.             sample->sample = NULL;
  1046.             sample->sdHandle = 0;
  1047.  
  1048.             /* Copy sample loop start and calculate loop end: */
  1049.             sample->loop1Start = s3mi.loopStart;
  1050.             sample->loop1End = s3mi.loopEnd;
  1051.  
  1052.             slength = s3mi.length;
  1053.  
  1054.             if ( ( s3mi.flags & 1 ) && ( s3mi.loopStart != s3mi.loopEnd ) )
  1055.             {
  1056.                 /* Looping sample - set loop types and limit sample length
  1057.                    to loop end: */
  1058.                 sample->loopMode = sdLoop1;
  1059.                 sample->loop1Type = loopUnidir;
  1060.                 if ( slength > sample->loop1End )
  1061.                     slength = sample->loop1End;
  1062.             }
  1063.             else
  1064.             {
  1065.                 /* Sample not looping: */
  1066.                 sample->loopMode = sdLoopNone;
  1067.                 sample->loop1Type = loopNone;
  1068.             }
  1069.  
  1070.             /* Set sample length: */
  1071.             sample->sampleLength = slength;
  1072.  
  1073.             /* Copy sample default volume: */
  1074.             sample->volume = s3mi.volume;
  1075.  
  1076.             /* No finetune used: */
  1077.             sample->finetune = 0;
  1078.  
  1079.             /* Copy sample base tune: */
  1080.             sample->baseTune = s3mi.c2Rate;
  1081.  
  1082.             /* Set sample default panning position to middle: */
  1083.             sample->panning = panMiddle;
  1084.  
  1085.             /* Check if there is sample data for this sample: */
  1086.             if ( slength != 0 )
  1087.             {
  1088.                 /* If sample data should not be added to Sound Device, allocate
  1089.                    memory for the sample data and point smpBuf there: */
  1090.                 if ( !addSD )
  1091.                 {
  1092.                     smpBuf = NULL;
  1093.                     if ( (error = memAlloc(slength, (void**)&smpBuf)) != OK )
  1094.                         PASSERR()
  1095.                     sample->sample = smpBuf;
  1096.                 }
  1097.                 else
  1098.                 {
  1099.                     /* Sample is added to the Sound Device - sample data is not
  1100.                        available: */
  1101.                     sample->sample = NULL;
  1102.                 }
  1103.  
  1104.                 /* Seek to instrument in file: */
  1105.                 if ( (error = fileSeek(f, 16L * s3mi.samplePtr, fileSeekAbsolute))
  1106.                     != OK )
  1107.                     PASSERR()
  1108.  
  1109.                 /* There is sample data - load sample: */
  1110.                 if ( (error = fileRead(f, smpBuf, slength)) != OK )
  1111.                     PASSERR()
  1112.  
  1113.                 /* Set Sound Device sample type: */
  1114.                 sdSmp.sampleType = smp8bit;
  1115.                 sample->sampleType = smp8bit;
  1116.  
  1117.                 /* Set Sound Device sample position in memory: */
  1118.                 sdSmp.samplePos = sdSmpConv;
  1119.  
  1120.                 /* Point Sound Device sample data to sample loading buffer: */
  1121.                 sdSmp.sample = smpBuf;
  1122.  
  1123.                 /* Point smpBuf to NULL if the sample is not added to Sound
  1124.                    Device to mark it should not be deallocated: */
  1125.                 if ( !addSD )
  1126.                     smpBuf = NULL;
  1127.             }
  1128.             else
  1129.             {
  1130.                 /* Mark there is no sample data: */
  1131.                 sdSmp.sampleType = smpNone;
  1132.                 sdSmp.samplePos = sdSmpNone;
  1133.                 sdSmp.sample = NULL;
  1134.             }
  1135.  
  1136.             sdSmp.sampleLength = slength;
  1137.             sdSmp.loopMode = sample->loopMode;
  1138.             sdSmp.loop1Start = sample->loop1Start;
  1139.             sdSmp.loop1End = sample->loop1End;
  1140.             sdSmp.loop1Type = sample->loop1Type;
  1141.  
  1142.  
  1143.             /* Set up the rest of Sound Device sample structure so that the sample
  1144.                can be added to the Sound Device: */
  1145.             if ( addSD )
  1146.             {
  1147.  
  1148.                 /* Add the sample to Sound Device and store the Sound Device
  1149.                    sample handle in sample->sdHandle: */
  1150.                 if ( (error = gmpSD->AddSample(&sdSmp, 1, &sample->sdHandle))
  1151.                     != OK)
  1152.                     PASSERR()
  1153.  
  1154.                 /* Call sample callback if used: */
  1155.                 if ( SampleCallback != NULL )
  1156.                 {
  1157.                     if ( (error = SampleCallback(&sdSmp, sample)) != OK )
  1158.                         PASSERR()
  1159.                 }
  1160.             }
  1161.             else
  1162.             {
  1163.                 /* Sample data has not been added to Sound Device: */
  1164.                 sample->sdHandle = 0;
  1165.             }
  1166.         }
  1167.         else
  1168.         {
  1169.             /* Sample is not used - there is no sample data: */
  1170.             inst->used = 0;
  1171.             inst->numSamples = 0;
  1172.         }
  1173.  
  1174. #ifdef DEBUGMESSAGES
  1175.         printf("Inst: %i, Len: %i\n", i, slength);
  1176. #endif
  1177.         CHECKHEAP
  1178.     }
  1179.  
  1180.     /* Deallocate sample loading buffer if allocated: */
  1181.     if ( addSD )
  1182.     {
  1183.         if ( (error = memFree(smpBuf)) != OK )
  1184.             PASSERR()
  1185.     }
  1186.     smpBuf = NULL;
  1187.  
  1188.     /* Deallocate instrument paragraph pointers: */
  1189.     if ( (error = memFree(instPtrs)) != OK )
  1190.         PASSERR()
  1191.     instPtrs = NULL;
  1192.  
  1193.     /* Deallocate instrument use flags: */
  1194.     if ( (error = memFree(instUsed)) != OK )
  1195.         PASSERR()
  1196.     instUsed = NULL;
  1197.  
  1198. #ifdef DEBUGMESSAGES
  1199.     puts("Samples ready");
  1200. #endif
  1201.     CHECKHEAP
  1202.  
  1203.     /* Now we are finished loading. Close module file: */
  1204.     if ( (error = fileClose(f)) != OK)
  1205.         PASSERR()
  1206.     fileOpened = 0;
  1207.  
  1208.     /* Deallocate Screamtracker module header: */
  1209.     if ( (error = memFree(header)) != OK )
  1210.         PASSERR();
  1211.  
  1212.     /* Return module pointer in *module: */
  1213.     *_module = module;
  1214.  
  1215. #ifdef DEBUGMESSAGES
  1216.     puts("Load Ok");
  1217. #endif
  1218.     CHECKHEAP
  1219.  
  1220.     return OK;
  1221. }
  1222.  
  1223.  
  1224. /*
  1225.  * $Log: loads3m.c,v $
  1226.  * Revision 1.15  1997/01/25 15:23:16  pekangas
  1227.  * The file is now closed properly if loading terminates to an error
  1228.  *
  1229.  * Revision 1.14  1997/01/16 18:41:59  pekangas
  1230.  * Changed copyright messages to Housemarque
  1231.  *
  1232.  * Revision 1.13  1996/12/30 23:38:08  jpaana
  1233.  * Cleaned up LoadError
  1234.  *
  1235.  * Revision 1.12  1996/09/08 21:00:42  pekangas
  1236.  * Fixed Set Tempo -command
  1237.  *
  1238.  * Revision 1.11  1996/09/05 06:28:28  pekangas
  1239.  * Changed S8 command to SetPanning16 (was SetPanning) (thanks Zapper)
  1240.  *
  1241.  * Revision 1.10  1996/09/01 15:42:31  pekangas
  1242.  * Changed to use new style slides (no more signed infobytes)
  1243.  *
  1244.  * Revision 1.9  1996/08/06 19:18:48  pekangas
  1245.  * Fixed to produce legal gmpModules so that mod2gm works
  1246.  *
  1247.  * Revision 1.8  1996/08/02 19:46:10  pekangas
  1248.  * Kluged to skip all instruments above module->numInsts to prevent crashes
  1249.  *
  1250.  * Revision 1.7  1996/07/16 17:35:35  pekangas
  1251.  * Fixed song data conversion loop
  1252.  *
  1253.  * Revision 1.6  1996/07/13 20:19:32  pekangas
  1254.  * Eliminated Visual C warnings
  1255.  *
  1256.  * Revision 1.5  1996/07/13 18:30:19  pekangas
  1257.  * Fixed to compile with Visual C
  1258.  *
  1259.  * Revision 1.4  1996/06/14 16:23:28  pekangas
  1260.  * Removed heap checking to speed up loading
  1261.  *
  1262.  * Revision 1.3  1996/05/24 17:03:24  pekangas
  1263.  * Fixed to work with Watcom C again - using EMPTYARRAY
  1264.  *
  1265.  * Revision 1.2  1996/05/24 16:20:36  jpaana
  1266.  * Fixed to work with gcc
  1267.  *
  1268.  * Revision 1.1  1996/05/22 20:49:33  pekangas
  1269.  * Initial revision
  1270.  *
  1271. */
  1272.